package com.atguigu.gmall.order.api;

import com.atguigu.gmall.common.result.Result;
import com.atguigu.gmall.common.util.AuthContextHolder;
import com.atguigu.gmall.order.model.OrderInfo;
import com.atguigu.gmall.order.service.OrderInfoService;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * 订单模块控制层
 */
@SuppressWarnings("all")
@RestController
@RequestMapping("/api/order")
public class OrderApiController {
    @Autowired
    private OrderInfoService orderInfoService;

    /**
     * 汇总订单确认页面需要的数据
     * @param request
     * @return
     */
    @GetMapping("/auth/trade")
    public Result OrderTrade(HttpServletRequest request){
       //1.获取当前登录用户的id
        String userId = AuthContextHolder.getUserId(request);
        //2.调用业务逻辑汇总处理业务数据
        Map<String,Object> mapResult = orderInfoService.trade(Long.valueOf(userId));
        return Result.ok(mapResult);
    }

    /**
     * 提交订单
     * @param request
     * @return
     */
    @PostMapping("auth/submitOrder")
    public Result submitOrder(HttpServletRequest request, @RequestBody OrderInfo orderInfo, @RequestParam("tradeNo") String tradeNo){
        String userId = AuthContextHolder.getUserId(request);
        orderInfo.setUserId(Long.valueOf(userId));
        Long orderId = orderInfoService.submitOrder(orderInfo,tradeNo);
        return Result.ok(orderId);
    }

    /**
     * 分页获取当前用户订单列表
     * @param request
     * @param page
     * @param limit
     * @return
     */
    @GetMapping("/auth/{page}/{limit}")
    public Result getOrderList(HttpServletRequest request,@PathVariable("page") Long page,@PathVariable("limit") Long limit){
       Page<OrderInfo> infoPage = new Page<>();
       //1.获取当前用户id
        String userId = AuthContextHolder.getUserId(request);
        infoPage = orderInfoService.getOrderList(infoPage,userId);
        return Result.ok(infoPage);
    }

    /**
     * 根据orderId查询订单信息,包含订单明细
     * @param orderId
     * @return
     */
    @GetMapping("/inner/getOrderInfo/{orderId}")
    public OrderInfo getOrderInfoByOrderId(@PathVariable("orderId") Long orderId){
        return orderInfoService.getOrderInfoByOrderId(orderId);
    }

    /**
     * 提供给库存系统拆单业务接口
     * @param orderId 订单id
     * @param wareSkuMap 系统查询到订单id和商品的对照关系, [{"wareId":"1","skuIds":["41"]},{"wareId":"2","skuIds":["26"]}]
     * @return 拆单后结果,包含每个订单对应每个仓库的id
     */
    @PostMapping("/orderSplit")
    public String orderSplit(@RequestParam("orderId") String orderId,@RequestParam("wareSkuMap") String wareSkuMap){
        return orderInfoService.orderSplit(orderId,wareSkuMap);
    }
}